#!/usr/bin/python
"""This module takes file containing sequences and generates output for ip solver.

The file taken as input is any alignment file containing sequences. Then it generates 
output which is in particular format, suitable to fed directly to glpsol which is an
ip solver. This could be extended for any solver but that would require modification in
output produced.
"""

# by Vineet Gupta <vineet@ural.wustl.edu>
# lp_gen.py 1-29-2007 01:57

# TO DO:
# check the correctness of the module

import sys
from sequence import Sequence
from alignment import Alignment
    
def main():
    try:
        a = Alignment(sys.argv[1])
        file = sys.argv[1]
    except:
        file = raw_input("Please enter file name: ")
        a = Alignment(file)
    
    # most distant sequence
    s_dist = Sequence(a.sequences[a.DisIdx])
    # total number of bases in each sequence
    n_bases = s_dist.Length
    # This will contain all the variables in cosensus sequence
    vars = ['y'+str(i) for i in range(0, 3*n_bases)]
    
    print "Maximize"
    print "\tZ:",
    
    for i in xrange(1, 3*n_bases+1):
        if int(s_dist.data[i-1]) == -1:
            temp = "- x" + str(i)
        elif i == 1:
            temp = "x" + str(i)
        else:
            temp = "+ x" + str(i)
        print temp,
    print
    
    print "Subject To"
    
    # Now iterate over all the constraints
    for i in xrange(a.Total):
        s = Sequence(a.sequences[i])
        #s.print_seq()
        flag = False
        print '\t',
        constant = 0
        for j in range(0, 3*n_bases):
            #print s.data[i], s_dist.data[i]
            c = (int)(s.data[j]) - (int)(s_dist.data[j])
            #print c

            if c > 0:
                temp = "+" + str(c) + " x" + str(j+1)
                constant += c
                print temp,
                flag = True
            elif c < 0:
                temp = str(c) + " x" + str(j+1)
                constant += c
                print temp,
                flag = True
            else:
                pass
        constant *= 2
        if flag:
            print ">", constant
            flag = False
            
    # printing bound constraint so that integer lies between 1 to 3
    
    print "Bounds"
    
    for i in range(0, 3*n_bases):
        print "\t1 <= x" + str(i+1) + " <= 3"            
            
    print "Integer"
    
    for i in range(0, 3*n_bases):
        print "\tx" + str(i+1)

    print "End"
    
if __name__ == '__main__':
    main()
